package com.flot.yazb.widget.utils;

/**
 * Created by fengdongfei on 2017/10/23.
 */

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;


/**
 * 满足第一种和第二种JSON的解析,data是object 和 外部object，内部含有list类型的json
 */
public class CommonJson<T> implements Serializable {

    private static final long serialVersionUID = -3440061414071692254L;

    @SerializedName("code")
    public String status;
    public String message;
    @SerializedName("data")
    public T content;
//    @SerializedName("data")
//    public List<T> content1;




    /**
     * JSON解析与组装代码
     * @param json
     * @param clazz
     * @return
     */
//    public static CommonJson fromJson(String json, Class clazz) {
//        Gson gson = new Gson();
//        Type objectType = type(CommonJson.class, clazz);
//        return gson.fromJson(json, objectType);
//    }

    /**
     * JSON解析与组装代码
     * @param
     * @return
     */
//    public String toJson(Class<T> clazz) {
//        Gson gson = new Gson();
//        Type objectType = type(CommonJson.class, clazz);
//        return gson.toJson(this, objectType);
//    }


    static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }



    public static <T> CommonJson<T> fromJsonObject(String reader, Class<T> clazz) {
        Type type = new ParameterizedTypeImpl(CommonJson.class, new Class[]{clazz});
        return new Gson().fromJson(reader, type);
    }

    public static <T> CommonJson<List<T>> fromJsonArray(String reader, Class<T> clazz) {
        // 生成List<T> 中的 List<T>
        Type listType = new ParameterizedTypeImpl(List.class, new Class[]{clazz});
        // 根据List<T>生成完整的Result<List<T>>
        Type type = new ParameterizedTypeImpl(CommonJson.class, new Type[]{listType});
        return new Gson().fromJson(reader, type);
    }

    public static class ParameterizedTypeImpl implements ParameterizedType {
        private final Class raw;
        private final Type[] args;

        public ParameterizedTypeImpl(Class raw, Type[] args) {
            this.raw = raw;
            this.args = args != null ? args : new Type[0];
        }

        @Override
        public Type[] getActualTypeArguments() {
            return args;
        }

        @Override
        public Type getRawType() {
            return raw;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }
}